package com.life.view;

import java.awt.Image;
import java.util.HashMap;

import javax.swing.SwingUtilities;

import com.life.constants.Constants;
import com.life.model.LifeModel;
import com.life.statistics.StatisticStruct;
import com.life.statistics.StatisticsElement;
import com.life.utils.ClusterStruct;

public class LifeStatisticsDrawingAdapter extends AbstractAdapter
{

    LifeCanvas theCanvas = null;
    LifeModel theModel = null; 
    
    public LifeStatisticsDrawingAdapter(LifeCanvas canvas)
    {
	theCanvas = canvas;
	theModel = theCanvas.getModel();
    }
    
    @Override
    public Object get()
    {
	// TODO Auto-generated method stub
	return null;
    }

    @Override
    public void set(Object data)
    {
	HashMap hash = (HashMap)data;
	
	if(hash.containsKey(Constants.RESET))
	{
	    theCanvas.repaint();
	}
	else if(hash.containsKey(Constants.SHOW_STATISTICS))
	{
	    showStatistics((StatisticStruct)hash.get(Constants.SHOW_STATISTICS));
	}	
        else if(hash.containsKey(Constants.SHOW_CLUSTERS))
    	{
            showClusters((ClusterStruct)hash.get(Constants.SHOW_CLUSTERS));
    	}
    }
    
    protected void showClusters(final ClusterStruct struct)
    {
	Thread newThread = new Thread()
	{
	    public void run()
	    {
		Image g = theCanvas.getDoubleBufferedImage();
		theCanvas.paint(g.getGraphics()); 
		for (int i = 0; i < struct.clusters.length; i++)
		{
		    for (int j = 0; j < struct.clusters[i].length; j++)
		    {
			int clusterNumber = struct.clusters[i][j];
			int count = struct.getClusterCount(clusterNumber);

			if (clusterNumber >= 0
				&& count > Constants.CLUSTER_THRESHOLD &&
				theModel.isAlive(i,j))
			{
			    theCanvas.drawAlive(i, j, g.getGraphics(), Constants.CLUSTER_COLOR);
			} else if (clusterNumber > 0 && count > 0
				&& count <= Constants.CLUSTER_THRESHOLD)
			{
			    theCanvas.drawAlive(i, j, g.getGraphics(), ColorGenerator
				    .getStatisticsColor());
			}
		    }
		}
		theCanvas.flushBuffer(g);
	    }
	};

	//theCanvas.repaint();
	SwingUtilities.invokeLater(newThread);
    }
    
    protected void showStatistics(final StatisticStruct struct)
    {
	Thread newThread = new Thread()
	{
	    public void run()
	    {
		Image g = theCanvas.getDoubleBufferedImage();
		theCanvas.paint(g.getGraphics()); 
		
		StatisticsElement[][] elements = struct.elements;

		for (int i = 0; i < elements.length; i++)
		{
		    for (int j = 0; j < elements[i].length; j++)
		    {
			if (elements[i][j].getSum() != 0)
			{
			    theCanvas.drawAlive(i, j,g.getGraphics(), ColorGenerator
				    .getStatisticsColor());
			}
		    }
		}
		theCanvas.flushBuffer(g);
	    }
	   
	};
	
	SwingUtilities.invokeLater(newThread);
    }

    @Override
    public void setEnabled(boolean value)
    {
	// TODO Auto-generated method stub

    }

}
